package com.itany.mall.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.List;

import com.itany.mall.dao.OrderDao;
import com.itany.mall.dao.mapper.OrderRowMapper;
import com.itany.mall.entity.Order;
import com.itany.mall.factory.Component;
import com.itany.mall.jdbc.template.JDBCTemplate;
import com.itany.mall.jdbc.template.KeyHolder;
import com.itany.mall.jdbc.template.callback.PreparedStatementCreater;

@Component
public class OrderDaoImpl implements OrderDao {

	@Override
	public long insert(Order order) {
		// 由于模板方法中有回调接口, 要对回调接口进行实现, 由模板方法使用
		PreparedStatementCreater creater = new PreparedStatementCreater() {
			@Override
			public PreparedStatement createPreparedStatement(Connection con) throws Exception {
				String sql = " insert into t_order(order_num, create_time, price, user_id) values (?, ?, ?, ?) ";
				PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
				ps.setObject(1, order.getOrderNum());
				ps.setObject(2, order.getCreateTime());
				ps.setObject(3, order.getPrice());
				ps.setObject(4, order.getUserId());
				// 由于该回调方法是被模板调用
				// 所以该回调方法的return是return给模板
				return ps;
			}
		};
		KeyHolder<Long> holder = new KeyHolder<Long>();
		// holder参数不是为了将数据传递进入方法
		// 而是为了将方法中的数据携带出来
		// 这种参数称为out型参数
		new JDBCTemplate<Long, Order>().update(creater, holder);
		return holder.getKey();
	}

	@Override
	public List<Order> selectByUserId(long userId) {
		OrderRowMapper mapper = new OrderRowMapper();
		String sql = mapper.selectSql() + " where u.id = ? ";
		return new JDBCTemplate<Long, Order>().query(sql, new Object[] { userId }, mapper);
	}

	@Override
	public Order selectByNumAndUserId(String num, long userId) {
		OrderRowMapper mapper = new OrderRowMapper();
		String sql = mapper.selectSql() + " where u.id = ? and o.order_num = ? ";
		List<Order> list = new JDBCTemplate<Long, Order>().query(sql, new Object[] { userId, num },
				mapper);
		return list != null && list.size() > 0 ? list.get(0) : null;
	}
}
